<template>
  <div class="search-page">
    <van-search
      placeholder="请输入搜索内容"
      class="search-bar"
      autofocus
      :show-action="!!keyword"
      v-model="keyword"
      @search="search"
    />
    <div class="search-type text-center" v-if="!keyword">
      <van-row gutter="16">
        <van-col
          span="6"
          :class="{ active: type == 'view' }"
          @click.native="$router.replace({ path: '/search', query: { type: 'view' }})"
        >观点</van-col>
        <van-col
          span="6"
          :class="{ active: type == 'live' }"
          @click.native="$router.replace({ path: '/search', query: { type: 'live' }})"
        >直播间</van-col>
        <van-col
          span="6"
          :class="{ active: type == 'portfolio' }"
          @click.native="$router.replace({ path: '/search', query: { type: 'portfolio' }})"
        >组合</van-col>
        <van-col
          span="6"
          :class="{ active: type == 'adviser' }"
          @click.native="$router.replace({ path: '/search', query: { type: 'adviser' }})"
        >投顾老师</van-col>
      </van-row>
    </div>
    <div class="text-center" v-else-if="loading">
      <van-loading/>
    </div>
    <div class="empty" v-else-if="isEmpty">
      找不到任何与“{{keyword}}”匹配的内容
    </div>
    <div class="search-result" v-else>
      <div class="block van-hairline--bottom " v-if="result[SEARCH_TYPE.VIEW] && result[SEARCH_TYPE.VIEW].length && (type == '' || type == 'view')">
        <van-cell v-if="!type" title="观点" value="更多相关观点" is-link @click.native="$router.push({ path: '/search', query: { type: 'view', q: keyword }});"/>
        <ul>
          <li class="view van-hairline--bottom" v-for="view in result[SEARCH_TYPE.VIEW]" :key="`view${view.id}`"
            @click="$router.push(`/view/detail/${view.id}`)"
          >
            <h3 class="van-ellipsis">{{view.name}}</h3>
            <div class="tg-info">
              <van-image lazy-load  :src="view.tgBaseInfo.avatar" round width="26px" height="26px"
              @click.native.stop="$router.push(`/adviser/detail/${view.tgBaseInfo.id}/`)"
              />
              <span>{{view.tgBaseInfo.name}}</span>
            </div>
          </li>
        </ul>
      </div>
      <div class="block van-hairline--bottom " v-if="result[SEARCH_TYPE.PORTFOLIO] && result[SEARCH_TYPE.PORTFOLIO].length && (type == '' || type == 'portfolio')">
        <van-cell v-if="!type" title="组合" value="更多相关组合" is-link @click.native="$router.push({ path: '/search', query: { type: 'portfolio', q: keyword }})" />
        <ul>
          <li class="portfolio van-hairline--bottom" v-for="portfolio in result[SEARCH_TYPE.PORTFOLIO]" :key="`portfolio${portfolio.id}`"
          @click="$router.push(`/portfolio/detail/${portfolio.id}`)"
          >
            <h3 class="van-ellipsis">{{portfolio.name}}</h3>
            <div class="tg-info">
              <van-image lazy-load  :src="portfolio.tgBaseInfo.avatar" round width="26px" height="26px"
              @click.native.stop="$router.push(`/adviser/detail/${portfolio.tgBaseInfo.id}/`)"
              />
              <span>{{portfolio.tgBaseInfo.name}}</span>
            </div>
          </li>
        </ul>
      </div>
      <div class="block van-hairline--bottom " v-if="result[SEARCH_TYPE.ADVISER] && result[SEARCH_TYPE.ADVISER].length && (type == '' || type == 'adviser')">
        <van-cell v-if="!type" title="投顾" value="更多相关投顾" is-link @click.native="$router.push({ path: '/search', query: { type: 'adviser', q: keyword }})" />
        <ul>
          <li class="adviser van-hairline--bottom" v-for="adviser in result[SEARCH_TYPE.ADVISER]" :key="`adviser${adviser.id}`"
          @click="$router.push(`/adviser/detail/${adviser.id}`)"
          >
            <van-image lazy-load  :src="adviser.tgBaseInfo.avatar" round width="35px" height="35px" />
            <span style="margin-left: 15px;">{{adviser.tgBaseInfo.name}}</span>
            <div class="follow">
              <i class="icon icon-follow"></i>
              <span>{{adviser.likeCount}}</span>
            </div>
          </li>
        </ul>
      </div>
      <div class="block van-hairline--bottom " v-if="result[SEARCH_TYPE.LIVE] && result[SEARCH_TYPE.LIVE].length && (type == '' || type == 'live')">
        <van-cell v-if="!type" title="直播" value="更多相关直播" is-link @click.native="$router.push({ path: '/search', query: { type: 'live', q: keyword }})" />
        <ul>
          <li class="live van-hairline--bottom" v-for="live in result[SEARCH_TYPE.LIVE]" :key="`live${live.id}`"
          @click="$router.push(`/live/${live.id}/history`)"
          >
            <van-image lazy-load  :src="live.tgBaseInfo.avatar" round width="35px" height="35px"
            @click.native.stop="$router.push(`/adviser/detail/${live.tgBaseInfo.id}/`)"
            />
            <div class="live-info">
              <div class="live-title">
                <h3 class="van-ellipsis">{{live.name}}</h3>
              </div>
              <p>{{live.tgBaseInfo.name}}</p>
            </div>
          </li>
        </ul>
      </div>
      <div class="text-center">
        <van-loading v-show="loadingMore" type="spinner" size="16px">加载中...</van-loading>
      </div>
    </div>
  </div>
</template>

<script>
import { Search, Cell, Loading } from "vant";
import { search } from '../api/common';
import debounce from 'lodash/debounce';
import trim from 'lodash/trim';

const SEARCH_TYPE = {
  LIVE: 1,
  VIEW: 2,
  PORTFOLIO: 3,
  ADVISER: 10,
}

export default {
  components: {
    [Search.name]: Search,
    [Cell.name]: Cell,
    [Loading.name]: Loading
  },

  props: {
    type: {
      type: String,
      default: ""
    },

    q: {
      type: String,
      default: ""
    }
  },

  data() {
    return {
      keyword: this.q,
      result: {},
      SEARCH_TYPE,
      loading: false,
      loadingMore: false,
      page: 1,
      size: 10
    };
  },

  computed: {
    isEmpty() {
      const keys = Object.keys(this.result);
      return keys.length && keys.reduce((pre, cur, i, arr) => {
        return pre.concat(this.result[cur])
      },[]).length === 0
    }
  },

  created() {
    document.body.style.background = "#fff";
    this.debouncedSearch = debounce(this.search, 500);
  },

  mounted() {
    this.$setTitle('搜索');
    if (this.q) {
      this.debouncedSearch(this.keyword);
    }
    this.$bus.$on('reachBottom', this.reachBottom.bind(this));
  },

  beforeDestroy() {
    document.body.style.background = "";
    this.$bus.$off('reachBottom');
  },

  methods: {
    async search(keyword) {
      try {
        keyword = trim(keyword);
        if(!keyword) return;
        this.loading = true;
        this.page = 1;
        const size = this.type ? this.size : 3;
        const data = await search({
          keyword,
          offset: (this.page - 1) * size,
          size: size,
          type: SEARCH_TYPE[this.type.toUpperCase()] || '1,2,3,10,11'
        });
        this.result = data.data;
      } catch (error) {
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    async reachBottom() {
      try {
        let keyword = this.keyword;
        keyword = trim(keyword);
        if(!keyword || !this.type) return;
        this.loadingMore = true;
        ++this.page;
        const type = SEARCH_TYPE[this.type.toUpperCase()];
        const data = await search({
          keyword,
          offset: (this.page - 1) * this.size,
          size: this.size,
          type
        });
        this.result[type] = this.result[type].concat(data.data[type]);
      } catch (error) {
        console.error(error);
      } finally {
        this.loadingMore = false;
      }
    }
  },

  watch: {
    keyword: function() {
      this.result = {};
      this.debouncedSearch(this.keyword);
    },

    type: function() {
      this.result = {};
      this.debouncedSearch(this.keyword);
    }
  }
};
</script>

<style lang="less">
.search-page {
  padding-top: 54px;

  .search-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 999;
  }
  .search-type {
    padding: 10px;
    .van-col {
      background-color: #f5f6f6;
      background-clip: content-box;
      color: #5e616b;
      line-height: 26px;
      font-size: 14px;

      &.active {
        background-color: #39a9ed;
        color: #fff;
      }
    }
  }

  .block {
    border-top: 10px solid #f5f6f6;

    .van-cell__title span {
      font-size: 18px;
      color: #2b313d;
      font-weight: bold;
    }

    .tg-info {
      display: flex;
      align-items: center;
      color: #9d9ea7;
      margin-top: 15px;

      span {
        margin-left: 15px;
        font-size: 14px;
      }
    }

    h3 {
      font-size: 16px;
    }

    .view, .portfolio, .adviser, .live {
      padding: 15px 0;
      margin: 0 15px;
    }

    .adviser {
      display: flex;
      align-items: center;

      .follow {
        flex: 1;
        text-align: right;
        color: #c3c4ca;
      }
    }

    .live {
      display: flex;
      align-items: center;
      color: #5e616b;

      .live-info {
        margin-left: 15px;
        p {
          margin-top: 5px;
        }
      }
    }

  }

  .empty {
    font-size: 14px;
    color: #9D9EA7;
    letter-spacing: 0;
    position: absolute;
    top: 30%;
    left: 50%;
    transform: translateX(-50%);
    text-align: center;
    width: 100%;
  }
}
</style>
